#!/bin/bash

# EmailQA Docker Deployment Script
# Usage: ./deploy.sh [development|testing|production]

set -e

ENVIRONMENT=${1:-development}

echo "🚀 Deploying EmailQA system in $ENVIRONMENT mode..."

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first."
    exit 1
fi

# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi

# Create necessary directories
echo "📁 Creating directories..."
mkdir -p data logs

# Copy environment file
if [ ! -f .env ]; then
    echo "📋 Copying environment file..."
    cp .env.$ENVIRONMENT .env
    echo "✅ Environment file created: .env"
else
    echo "ℹ️  Environment file already exists: .env"
fi

# Stop existing containers
echo "🛑 Stopping existing containers..."
docker-compose down

# Build and start services
echo "🏗️  Building and starting services..."
if [ "$ENVIRONMENT" = "production" ]; then
    docker-compose up -d --build
else
    docker-compose --profile mcp up -d --build
fi

# Wait for services to be ready
echo "⏳ Waiting for services to be ready..."
sleep 30

# Health check
echo "🔍 Performing health check..."
if curl -f http://localhost:5000/api/health > /dev/null 2>&1; then
    echo "✅ EmailQA API is healthy"
else
    echo "❌ EmailQA API is not responding"
    exit 1
fi

# Show running containers
echo "📦 Running containers:"
docker-compose ps

echo "🎉 Deployment completed successfully!"
echo "📊 API Documentation: http://localhost:5000/docs/"
echo "🔗 Health Check: http://localhost:5000/api/health"

if [ "$ENVIRONMENT" != "production" ]; then
    echo "🔧 MCP Server is running in development mode"
fi